package com.irononetech.android.formcomponent.view;

import java.io.File;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.irononetech.android.Application.Application;
import com.irononetech.android.Webservice.URL;
import com.irononetech.android.draftserializer.FormObjSerializer;
import com.irononetech.android.fileio.FileOperations;
import com.irononetech.android.formcomponent.FormObject;
import com.irononetech.android.formcomponent.FormResubmitObject;
import com.irononetech.android.homecomponent.HomeActivity;
import com.irononetech.android.network.NetworkCheck;
import com.irononetech.android.template.EventParcel;
import com.irononetech.android.template.UIEvent;
import com.irononetech.android.claimsonersa.R;
import com.irononetech.android.utilities.JPGFileFilter;

public class CommentActivity extends Activity {

	FormObject formObject;
	public ProgressDialog dialog;
	InputMethodManager imm;
	EditText appCostRprTxtbox;
	Spinner onsiteestimation;
	EditText commentsTxtbox;
	
	Button buttonSubmit;
	
	Logger LOG = LoggerFactory.getLogger(CommentActivity.class);
	
	public synchronized ProgressDialog getDialog() {
		return dialog;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			LOG.debug("ENTRY onCreate");
			if(Application.goForward)
				overridePendingTransition(R.anim.slide_left, R.anim.slide_left);
			if(Application.goBackward)
				overridePendingTransition(R.anim.slide_right, R.anim.slide_right);
			setContentView(R.layout.commentform);
			
			imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			formObject = Application.getFormObjectInstance();
			
			appCostRprTxtbox = (EditText) findViewById(R.id.appCostRprTxtbox);
			onsiteestimation = (Spinner) findViewById(R.id.onsiteestimation_spinner);
			ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
					this, R.array.onsiteestOpt, R.layout.textviewforspinner);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			onsiteestimation.setAdapter(adapter);
			onsiteestimation
					.setOnItemSelectedListener(new MyOnItemSelectedListenerOnSiteEstimation());
			onsiteestimation.setSelection(Integer.parseInt(formObject.getOnSiteEstimation().trim()));
			
			commentsTxtbox = (EditText) findViewById(R.id.commentsTxtbox);
			buttonSubmit = (Button)findViewById(R.id.commentform_submit_button);

			formComponentControler();
			onLoad();
			LOG.debug("SUCCESS onCreate");
		} catch (NumberFormatException e) {
			LOG.error("onCreate:10430");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		} catch (Exception e) {
			LOG.error("onCreate:10431");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	@Override
	protected void onResume() {
		try {
			super.onResume();
			LOG.debug("ENTRY onResume");
			if(Application.goForward)
				overridePendingTransition(R.anim.slide_left, R.anim.slide_left);
			if(Application.goBackward)
				overridePendingTransition(R.anim.slide_right, R.anim.slide_right);

			formComponentControler();
			onLoad();
			LOG.debug("SUCCESS onResume");
		} catch (Exception e) {
			LOG.error("onResume:10431");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	@Override
	protected void onPause() {
		try {
			super.onPause();
			LOG.debug("ENTRY onPause");
			System.gc();
			LOG.debug("SUCCESS onPause");
		} catch (Exception e) {
			LOG.error("onResume:10432");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}

	public void formComponentControler(){
		try {
			if(formObject.getisDRAFT() || formObject.getisSMS()){/*
				onsiteestimation.setEnabled(true);	
								
				appCostRprTxtbox.setFocusable(true);
				appCostRprTxtbox.setFocusableInTouchMode(true); 
				appCostRprTxtbox.setClickable(true);

				commentsTxtbox.setFocusable(true);
				commentsTxtbox.setFocusableInTouchMode(true); 
				commentsTxtbox.setClickable(true); */
				int maxLength = 500;
				InputFilter[] fArray = new InputFilter[1];
				fArray[0] = new InputFilter.LengthFilter(maxLength);
				commentsTxtbox.setFilters(fArray);
				}
			if(formObject.getisSEARCH()){
				onsiteestimation.setEnabled(false);

				appCostRprTxtbox.setTextColor(Color.GRAY);
				appCostRprTxtbox.setFocusable(false);
				appCostRprTxtbox.setFocusableInTouchMode(false); 
				appCostRprTxtbox.setClickable(false);

				commentsTxtbox.setTextColor(Color.GRAY);
				commentsTxtbox.setFocusable(false);
				commentsTxtbox.setFocusableInTouchMode(false); 
				commentsTxtbox.setClickable(false);
				commentsTxtbox.setTextSize(22);

				buttonSubmit.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			LOG.error("formComponentControler:10432");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			//return false;
			//Application.cancelForm(this);
			Application.getInstance().doActionOnEvent(new EventParcel(UIEvent.CANCEL_FORM, this, null));
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void onClick_keyboardClose(View v){
	    v.setOnClickListener(new View.OnClickListener() {
	        
	    	@Override
	        public void onClick(View v) {
	            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	        }
	    });
	}
	
	public void onLoad() {
		try {
			appCostRprTxtbox.setText(formObject.getAppCost());
			onsiteestimation.setSelection(Integer.parseInt(formObject.getOnSiteEstimation().trim()));
			//if(!formObject.getisSEARCH()){
				commentsTxtbox.setText(formObject.getComments());
			//}
		} catch (NumberFormatException e) {
			LOG.error("onLoad:10433");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	public void onSave(){
		try {
			formObject.setAppCost(appCostRprTxtbox.getText().toString().trim());

			int pos = onsiteestimation.getSelectedItemPosition();
			for (CommentOpt fm : CommentOpt.values()) {
				if (onsiteestimation.getItemAtPosition(pos).toString().equals(fm.getString())) {
					formObject.setOnSiteEstimation(Integer.toString(fm.getInt()));
					break;
				}
			}
			formObject.setComments(commentsTxtbox.getText().toString().trim());

			if(!formObject.getisSEARCH()){
				FormObjSerializer.serializeFormData(formObject);
			}
		} catch (Exception e) {
			LOG.error("onSave:10434");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}

	public void on_click_back_button(View v){
		 try {
			 LOG.debug("ENTRY ",  "on_click_back_button");
			 Application.goForward = false;
			 Application.goBackward = true;
			 onSave();
			 Application.getInstance().doActionOnEvent(new EventParcel(UIEvent.COMMENTFORM_BACK_BUTTON_CLICK, this, formObject));
			 LOG.debug("SUCCESS ","on_click_back_button");
		 } catch (Exception e) {
			 LOG.error("onCron_click_back_button:10435eate");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		 }
	}
	
	public void on_click_cancel_button(View v){
		//Application.cancelForm(this);
		Application.getInstance().doActionOnEvent(new EventParcel(UIEvent.CANCEL_FORM, this, null));
	}

	public void on_click_submit_button(View v){
		try {
			LOG.debug("ENTRY ", "on_click_submit_button");

			if (Application.getIsOnline() == 0) { //If Offline   0==Offline

				AlertDialog.Builder alertbox = new AlertDialog.Builder(CommentActivity.this);
				alertbox.setTitle("Motor Claim Form:");
				alertbox.setMessage("Do the job submission in online mode.");
				alertbox.setPositiveButton("Save & Goto Home",
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						onSave();

						Intent mIntent = new Intent(CommentActivity.this, HomeActivity.class);
						mIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						CommentActivity.this.startActivity(mIntent);
						CommentActivity.this.finish();
					}});
				alertbox.setNegativeButton("Ok",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						removeDialog(arg1);
					}});
				alertbox.show();

			} else if (!NetworkCheck.isNetworkAvailable(this)) {//If No network
				AlertDialog.Builder alertbox = new AlertDialog.Builder(CommentActivity.this);
				alertbox.setTitle("Motor Claim Form:");
				alertbox.setMessage(R.string.submit_no_network_msg);
				alertbox.setPositiveButton("Ok",
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						removeDialog(arg1);
					}});
				alertbox.show();
			} else { //If Online

				//Set the image count
				File f = new File(URL.getSLIC_JOBS() + formObject.getJobNo());
				if(f.exists()){
					List<File> fileList = FileOperations.listFiles(f, new JPGFileFilter(), true);

					if(!formObject.getisSEARCH()){
						formObject.setImageCount(Integer.toString(fileList.size()));
					}
				}

				//Set the random number as reference no
				Random randomGenerator = new Random();
				int randomInt = randomGenerator.nextInt(Integer.MAX_VALUE);

				//Application.deleteFormResubmitObjectInstance();
				FormResubmitObject objR = Application.createFormResubmitObjectInstance();
				objR.setisSEARCH(Application.getFormObjectInstance().getisSEARCH());
				objR.setRefNo(randomInt+"");
				formObject.setRefNo(randomInt+"");

				AlertDialog.Builder alertbox = new AlertDialog.Builder(
						CommentActivity.this);
				alertbox.setTitle("Motor Claim Form:");
				alertbox.setMessage("Are you sure you want to submit?");
				alertbox.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						onSave();
						//if(Application.automaticlogin())
							Application.getInstance().doActionOnEvent(new EventParcel(UIEvent.SUBMIT_BUTTON_CLICK, CommentActivity.this, formObject));
					}
				});
				alertbox.setNegativeButton("No",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {
						removeDialog(arg1);
					}
				});
				alertbox.show();
			}
			LOG.debug("SUCCESS ","on_click_submit_button");
		} catch (Exception e) {
			LOG.error("on_click_submit_button:10437");
			   if(e != null){
				LOG.error("Message: " + e.getMessage());
				LOG.error("StackTrace: " + e.getStackTrace());
			  }
		}
	}
	
	public class MyOnItemSelectedListenerOnSiteEstimation implements
	OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			try {
				((TextView) parent.getChildAt(0)).setBackgroundDrawable(getResources().getDrawable(R.drawable.motorclaims_spinneritem_bg));
				
				if(formObject.getisSEARCH())
					((TextView) parent.getChildAt(0)).setTextColor(Color.GRAY);
				
				for (Confirmation fm : Confirmation.values()) {
					if (parent.getItemAtPosition(pos).toString()
					.equals(fm.getString())) {
						formObject.setOnSiteEstimation(Integer.toString(fm.getInt()));
						break;
					}
				}
			} catch (Exception e) {
				LOG.error("onItemSelected:10438");
				   if(e != null){
					LOG.error("Message: " + e.getMessage());
					LOG.error("StackTrace: " + e.getStackTrace());
				  }
			}
		}
		
		public void onNothingSelected(AdapterView parent) {
			// Do nothing.
		}
	}
}